from collections import OrderedDict
from datetime import datetime
from time import time
import json

from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from .serializer import *
from util.auth import OWNTokenAuthentication
from util.page import MyPageNumberPagination
from util.exception import ValidationError
from util.xlstool import XlsTool
from .models import *


class OrderView(GenericViewSet):
    authentication_classes = [OWNTokenAuthentication]

    @action(detail=False, methods=["GET", ], url_path="order_list")
    def order_list(self, requests, *args, **kwargs):
        order_id = requests.GET.get("order_id", None)
        custom_name = requests.GET.get("custom_name", None)
        custom_name_number = requests.GET.get("custom_name_number", None)
        custom_company_number = requests.GET.get("custom_company_number", None)
        custom_company = requests.GET.get("custom_company", None)
        custom_phone = requests.GET.get("custom_phone", None)
        start_date = requests.GET.get("start_date", None)
        end_date = requests.GET.get("end_date", None)
        data = {
            "order_id": order_id if order_id else None,
            "custom_name": custom_name if custom_name else None,
            "custom_name_number": custom_name_number if custom_name_number else None,
            "custom_company_number": custom_company_number if custom_company_number else None,
            "custom_company": custom_company if custom_company else None,
            "custom_phone": custom_phone if custom_phone else None,
            "start_date": start_date if start_date else None,
            "end_date": end_date if end_date else None,
        }
        serializers = OrderCheckSerializer(data=data)
        if serializers.is_valid():
            orders = OrderModel.objects
            order_id = serializers.validated_data.get("order_id")
            custom_name = serializers.validated_data.get("custom_name")
            custom_name_number = serializers.validated_data.get("custom_name_number")
            custom_company = serializers.validated_data.get("custom_company")
            custom_company_number = serializers.validated_data.get("custom_company_number")
            custom_phone = serializers.validated_data.get("custom_phone")
            start_date = serializers.validated_data.get("start_date")
            end_date = serializers.validated_data.get("end_date")
            if order_id:
                orders = orders.filter(order_id__icontains=order_id)
            if custom_name:
                orders = orders.filter(custom_name__icontains=custom_name)
            if custom_name_number:
                orders = orders.filter(custom_name_number__icontains=custom_name_number)
            if custom_company:
                orders = orders.filter(custom_company__icontains=custom_company)
            if custom_company_number:
                orders = orders.filter(custom_company_number__icontains=custom_company_number)
            if custom_phone:
                orders = orders.filter(custom_phone__icontains=custom_phone)
            if start_date and end_date:
                orders = orders.filter(order_date__gt=start_date, order_date__lt=end_date)
            orders = orders.filter(is_delete=False).all()
            page = MyPageNumberPagination()
            page_usrs = page.paginate_queryset(queryset=orders, request=requests, view=self)
            gateway_re = OrderListSerializer(instance=page_usrs, many=True)
            return Response(self.__get_paginated_response(page, requests, gateway_re.data))
        else:
            raise ValidationError(20001)

    def __get_paginated_response(self, page, request, datas):
        a = OrderedDict([
            ('current', int(page.get_page_number(request, page))),
            ('total', int(page.page.paginator.count)),
            ('pageSize', int(page.get_page_size(request))),
            ('data', datas),
            ("code", 200)
        ])
        return a

    @action(detail=False, methods=["POST", ], url_path="fileupload")
    def mupload(self, requests, *args, **kwargs):
        file_path = os.path.dirname(os.path.abspath(__file__))
        base_path = os.path.join(file_path, 'temp.xlsx')
        myFile = requests.FILES.get("file")
        if not myFile:
            raise ValidationError(50002)
        destination = open(base_path, "wb+")
        for chunk in myFile.chunks():
            destination.write(chunk)
        destination.close()
        x = XlsTool(base_path)
        data = x.get_all()
        serializer = orderCheckSerializer(data=data)
        serializer.create(data)
        os.remove(base_path)
        return Response({
            "code": 200,
            "msg": "上传成功",
        })

    @action(detail=False, methods=["POST", ], url_path="order_create")
    def file_version_create(self, requests, *args, **kwargs):
        order_id = requests.query_params.get("order_id", None)
        custom_name = requests.query_params.get("custom_name", None)
        custom_name_number = requests.query_params.get("custom_name_number", None)
        custom_company_number = requests.query_params.get("custom_company_number", None)
        custom_company = requests.query_params.get("custom_company", None)
        custom_phone = requests.query_params.get("custom_phone", None)
        order_date = requests.query_params.get("order_date", None)
        data = {
            "order_id": order_id if order_id else "",
            "custom_name": custom_name if custom_name else "",
            "custom_name_number": custom_name_number if custom_name_number else "",
            "custom_company_number": custom_company_number if custom_company_number else "",
            "custom_company": custom_company if custom_company else "",
            "custom_phone": custom_phone if custom_phone else "",
            "order_date": order_date if order_date else ""
        }
        serializer = orderCreateSerializer(data=data)
        if serializer.is_valid():
            serializer.create(serializer.validated_data)
            return Response({"code": 200, "msg": "添加成功"})
        raise ValidationError(20001)

    @action(detail=False, methods=["POST", ], url_path="order_update")
    def order_update(self, requests, *args, **kwargs):
        id=requests.query_params.get("id", None)
        order_id = requests.query_params.get("order_id", None)
        custom_name = requests.query_params.get("custom_name", None)
        custom_name_number = requests.query_params.get("custom_name_number", None)
        custom_company_number = requests.query_params.get("custom_company_number", None)
        custom_company = requests.query_params.get("custom_company", None)
        custom_phone = requests.query_params.get("custom_phone", None)
        order_date = requests.query_params.get("order_date", None)
        data = {
            "id": id if id else "",
            "order_id": order_id if order_id else "",
            "custom_name": custom_name if custom_name else "",
            "custom_name_number": custom_name_number if custom_name_number else "",
            "custom_company_number": custom_company_number if custom_company_number else "",
            "custom_company": custom_company if custom_company else "",
            "custom_phone": custom_phone if custom_phone else "",
            "order_date": order_date if order_date else ""
        }
        serializer = orderUpdateSerializer(data=data)
        if serializer.is_valid():
            serializer.update_order(serializer.validated_data)
            return Response({"code": 200, "msg": "修改成功"})
        raise ValidationError(20001)

